#!/bin/gawk -f
# Summarize RESTRAINT_VIOLATIONS from .nrc/.hrc/.src file
# Input: data record with all restraint violations, sorted on column $num
# Script prints the largest violations on aqsumm.tmp
# and the average and rms values on aqsumm.tmp2 (if aver).
# Argument : aver (0/1)
#
# Note on printf statement: the residue 'number' is printed as %4s, since it
# may contain an insertion code.

BEGIN { 
    pr = 1
    if  ( numlin <= 0 ) numlin = 3
}
pr {
    if ( $num != exitval && NR > numlin ) pr = 0
    if ( NR == numlin ) exitval = $num
    if ( pr && $num != 0. ) {
# can't have a variable format - see postprocessing in aqsumm
        if ( $1 == "_" && $5 == "_" && oldstyle )
            printf( "%5s %4s %-5s  %5s %4s %-5s %.2f\n",
                    $2,$3,$4,$6,$7,$8,$num ) > "aqsumm.tmp"
        else
	    printf( "%s %5s %4s %-5s  %s %5s %4s %-5s %.2f\n",
	            $1,$2,$3,$4,$5,$6,$7,$8,$num ) > "aqsumm.tmp"
    }
}
aver {
    if ( $num > 0. ) {
	totu += $num
	totu2 += $num * $num
	ctu++
    }
    if ( $num < 0. ) {
	totl += $num
	totl2 += $num * $num
	ctl++
    }
    ct++
}
END {
#...add rms values
    if ( aver ) {
	printf("\n(from restraint violation list:)\n") > "aqsumm.tmp2"
	printf("Total UPPER BOUND violation: %.2f\n", totu) > "aqsumm.tmp2"
	printf("Number of violated restraints: %5i, Average violation: %.2f\n", ctu, totu/ctu) > "aqsumm.tmp2"
	printf("Number of restraints:          %5i, Average violation: %.3f\n", ct, totu/ct) > "aqsumm.tmp2"
	printf("Total LOWER BOUND violation: %.2f\n", totl) > "aqsumm.tmp2"
	if ( ctl == 0 && totl == 0. ) val = 0.
	else val = totl/ctl
	printf("Number of violated restraints: %5i, Average violation: %.2f\n", ctl, val) > "aqsumm.tmp2"
	printf("Number of restraints:          %5i, Average violation: %.3f\n\n", ct, totl/ct) > "aqsumm.tmp2"
    }
} 
